// cloudfunctions/createComment/index.js
const cloud = require('wx-server-sdk');
cloud.init({
  env: cloud.DYNAMIC_CURRENT_ENV
});
const db = cloud.database();
const _ = db.command;

exports.main = async (event, context) => {
  try {
    const { postId, content, userId, userName, userAvatar, replyTo, replyToUser } = event;
    
    // 验证必要参数
    if (!postId || !content || !userId || !userName || !userAvatar) {
      return { success: false, message: '缺少必要参数' };
    }
    
    // 保存评论
    const result = await db.collection('community_comments').add({
      data: {
        postId,
        content,
        userId,
        userName,
        userAvatar,
        likeCount: 0,
        likeList: [],
        createTime: db.serverDate(),
        updateTime: db.serverDate(),
        replyTo,               // 回复的评论ID（顶级评论为null）
        replyToUser,           // 回复的用户名称
        replyCount: 0,          // 回复数量
        status: 'normal'        // 评论状态
      }
    });
    
    // 更新帖子评论数
    await db.collection('community_posts').doc(postId).update({
      data: {
        commentCount: _.inc(1)
      }
    });
    
    // 如果是回复，更新被回复评论的回复数
    if (replyTo) {
      await db.collection('community_comments').doc(replyTo).update({
        data: {
          replyCount: _.inc(1)
        }
      });
    }
    
    return {
      success: true,
      data: { commentId: result._id },
      message: '创建评论成功'
    };
  } catch (error) {
    console.error('创建评论失败', error);
    return {
      success: false,
      message: error.message || '服务器错误',
      error: error.message
    };
  }
};